package ebcs.scan.common.filter;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ebcs.database.bean.BsUserInfor;
import ebcs.scan.common.consts.SessConsts;
import ebcs.scan.common.utils.StringUtil;
 

public class SessionFilter implements Filter {
    private final static Log logger = LogFactory.getLog(SessionFilter.class);
     /**
     * 过滤器配置
     */
    private FilterConfig filterConfig;

    /**
     * 超时页面
     */
    protected String sessionTimeOutPage = null;

    /**
     * 某些url前缀列表(如: /css/*, /js/*, /images/***...)
     */
    private List<String> ignoreURIs = new ArrayList<String>();

    /**
     * 静态资源列表(如: *.css, *.js, *.jpg...)
     */
    private List<String> ignoreExts = new ArrayList<String>();

    /**
     * 个别动态资源(如: login.action, navigate.action, login.jsp...)
     */
    private List<String> ignoreActions = new ArrayList<String>();

    /**
     * Default Construct.
     */
    public SessionFilter() {
        super(); 
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("Init SessionFilter Start.");
        this.filterConfig = filterConfig;
        // this.context = this.filterConfig.getServletContext();
        // startMonitor();

        // 某些URL前缀不予处理（例如 /img/***）
        String ignores = filterConfig.getInitParameter("ignoreURIs");
        if (ignores != null) {
            for (String ig : StringUtils.split(ignores, ',')) {
                ignoreURIs.add(ig.trim());
            }
        }

        // 某些URL扩展名不予处理(例如 *.jpg)
        ignores = filterConfig.getInitParameter("ignoreExts");
        if (ignores != null) {
            for (String ig : StringUtils.split(ignores, ',')) {
                ignoreExts.add('.' + ig.trim());
            }
        }

        // 某写页面及Action不予处理(例如login.jsp,login.action)
        ignores = filterConfig.getInitParameter("ignoreActions");
        if (ignores != null) {
            for (String ig : StringUtils.split(ignores, ',')) {
                ignoreActions.add(ig.trim());
            }
        }

        logger.info("Init sessionFilter End.");
    }

    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setHeader("Access-Control-Allow-Origin", "http://192.168.1.107:3004");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "content-type");
        // HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);
        resp.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(true);
        String requestUrl = req.getRequestURI();
        String redirectPath = req.getContextPath() + "/page/login.do";
        showHeadValues(req);
        try {
        	logger.info("requestUrl-->"+requestUrl);
            //过滤URL前缀
			for (String ignoreURI : ignoreURIs) {
				if (requestUrl.startsWith(ignoreURI)) {
					chain.doFilter(req, resp);
					return;
				}
			}

            //过滤URL后缀
            for (String ignoreExt : ignoreExts) {
                if (requestUrl.endsWith(ignoreExt)) {
                    chain.doFilter(req, resp);
                    return;
                }
            }

            // 过滤登陆action/jsp
            for (String ingonAction : ignoreActions) {
                if (isContains(requestUrl, ingonAction)) {
                    chain.doFilter(req, resp);
                    return;
                }
            }

            if (requestUrl.endsWith("/dolphine/") || requestUrl.endsWith("/dolphine")) {
                resp.sendRedirect(redirectPath);
                return;
            }
        } catch (SecurityException e) {
            String loginPage = req.getContextPath() + URLEncoder.encode(requestUrl, "utf-8");
            resp.sendRedirect(loginPage);
        }
      //  chain.doFilter(request, response);
    	//logger.info("IPMS SESSION LOG :SESSIONID="+session.getId()+";ISNEWSESSION="+session.isNew());
        // 验证session是否过期
        BsUserInfor user = (BsUserInfor)session.getAttribute(SessConsts.CUSTINFO);
        if (user == null) {
            // 此处考虑ajax操作session过期的操作，如果ajax请求过程中session过期，则指定过期状态码为：911.
            String requestType = req.getHeader("X-Requested-With");
            if (StringUtil.isNotEmpty(requestType) && requestType.equalsIgnoreCase("XMLHttpRequest")) {
                resp.setStatus(911);
                resp.setHeader("sessionstatus", "timeout");
                resp.addHeader("loginPath", redirectPath);
                return;
            } else {
                // wrapper.sendRedirect(redirectPath);
                resp.sendRedirect(redirectPath);
                return;
            }
        } else {
            chain.doFilter(request, response);
            return;
        }
    }

    public static boolean isContains(String container, String regx) {
        boolean result = false;

        if (container.indexOf(regx) != -1) {
            return true;
        }
        return result;
    }
    
    
    /**
	 * 显示请求内容
	 * 
	 * @param request
	 */
	private void showHeadValues(HttpServletRequest request)
	{
		Enumeration e = request.getHeaderNames();

		StringBuffer sbuffer = new StringBuffer();
		sbuffer.append("REALIP=").append(StringUtil.getIpAddr(request))
		.append(request.getRemoteHost())
		.append(":").append(request.getRemotePort()).append("\n");
		while (e.hasMoreElements()) {
			String a = (String) e.nextElement();
			sbuffer.append(a).append(":").append(request.getHeader(a)).append("\n");
		}

		logger.info(sbuffer.toString());
	}


}
